package com.woniu.woniuproject.realms;

import com.woniu.woniuproject.entity.Admin;
import com.woniu.woniuproject.entity.User;
import com.woniu.woniuproject.service.AdminService;
import com.woniu.woniuproject.service.UsersService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 功能描述:<br>
 * 〈〉
 * @author wugd
 * @create 2020/11/9
 * @since 1.0.0
 */
public class ShiroRealm extends AuthorizingRealm {
    @Autowired
    AdminService adminService;
    @Autowired
    UsersService usersService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken token1= (UsernamePasswordToken) token;
        String account=token1.getUsername();
        if(account.endsWith("*")){
            String substring = account.substring(0, account.length() - 1);
            User user= usersService.queryUserByName(substring);
            if (user!=null){
                SecurityUtils.getSubject().getSession().setAttribute("loginUser",user);
                ByteSource salt=ByteSource.Util.bytes(user.getUsername());
                SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(user,user.getPassword(),salt,this.getName());
                return info;
            }
        }else{
            Admin admin=adminService.queryAdminByName(account);
            //加盐加密
            if (admin!=null){
                SecurityUtils.getSubject().getSession().setAttribute("loginAdmin",admin);
                ByteSource salt=ByteSource.Util.bytes(admin.getAdminname());
                SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(admin,admin.getPassword(),salt,this.getName());
                return info;
            }
        }
        throw new UnknownAccountException("账号不存在");
    }
    public static void main(String[] args) {
        SimpleHash simpleHash = new SimpleHash("MD5", "123", "123", 1024);
        System.out.println(simpleHash.toString());

    }
}
